package com.sgcc.nfc.lock.presentation.rooms

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sgcc.nfc.lock.core.network.NetworkResult
import com.sgcc.nfc.lock.domain.model.Room
import com.sgcc.nfc.lock.domain.model.RoleType
import com.sgcc.nfc.lock.domain.usecase.GetProfileUseCase
import com.sgcc.nfc.lock.domain.usecase.GetRoomsUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@HiltViewModel
class RoomsViewModel @Inject constructor(
    private val getRoomsUseCase: GetRoomsUseCase,
    private val getProfileUseCase: GetProfileUseCase
) : ViewModel() {

    private val _rooms = MutableLiveData<List<Room>>(emptyList())
    val rooms: LiveData<List<Room>> = _rooms

    private val _isLoading = MutableLiveData(false)
    val isLoading: LiveData<Boolean> = _isLoading

    private val _error = MutableLiveData<String?>()
    val error: LiveData<String?> = _error

    private var searchJob: Job? = null
    private var keywordCache: String? = null
    private var regionFilterId: Long? = null
    private var profileLoaded = false

    init {
        loadRooms()
    }

    fun loadRooms(keyword: String? = null) {
        keywordCache = keyword
        viewModelScope.launch {
            _isLoading.value = true
            _error.value = null

            // 确保已获取用户权限信息
            ensureRegionFilter()

            when (val result = getRoomsUseCase(
                page = 1,
                pageSize = 100,
                regionId = regionFilterId,
                keyword = keyword
            )) {
                is NetworkResult.Success -> {
                    _rooms.value = result.data.data
                }
                is NetworkResult.Error -> {
                    _error.value = result.message
                    _rooms.value = emptyList()
                }
                is NetworkResult.Loading -> {
                    // Loading state already handled
                }
            }

            _isLoading.value = false
        }
    }

    fun search(keyword: String) {
        searchJob?.cancel()
        searchJob = viewModelScope.launch {
            delay(300) // 防抖动
            loadRooms(keyword.takeIf { it.isNotBlank() })
        }
    }

    fun currentKeyword(): String? = keywordCache

    private suspend fun ensureRegionFilter() {
        if (profileLoaded) return

        when (val profileResult = getProfileUseCase()) {
            is NetworkResult.Success -> {
                val user = profileResult.data
                val role = RoleType.fromValue(user.roleType)
                
                // 根据用户角色设置区域过滤
                regionFilterId = when (role) {
                    RoleType.SUPER_ADMIN, RoleType.PROVINCE_ADMIN -> null // 可以查看所有区域
                    else -> user.regionId // 只能查看自己区域的房间
                }
                profileLoaded = true
            }
            is NetworkResult.Error -> {
                // 如果获取用户信息失败，不设置区域过滤
                regionFilterId = null
                profileLoaded = true
            }
            is NetworkResult.Loading -> {
                // Loading state handled
            }
        }
    }
}
